package com.lvmama.search.spider.proxy;

import java.util.ArrayList;
import java.util.List;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.http.HttpStatus;

import com.lvmama.search.spider.config.ContentFetchConfig;
import com.lvmama.search.spider.config.FetchResult;
import com.lvmama.search.spider.worker.DefaultContentFetcher;

public class ProxyValidator {
	
	private static Log log=LogFactory.getLog(ProxyValidator.class);
	
	static DefaultContentFetcher contentFetcher=new DefaultContentFetcher();
	public static boolean  isProxyValidate(ProxyIp ip) {
		try {
			ContentFetchConfig config=new ContentFetchConfig();
			config.setConTimeout(3000);
			config.setSoTimeout(5000);
			config.setUrl("http://www.baidu.com");
			config.setMethod("get");
			config.setProxyIp(ip);
			FetchResult result=contentFetcher.getPageContent(config);
			boolean checkResult= result!=null&&result.getStatusCode()==HttpStatus.SC_OK&&!result.isError();
			log.info(ip+",check result:"+checkResult);
			return checkResult;
		} catch (Exception e) {
			log.error("erro while validate proxy ip:"+ip,e);
		}
		return false;
	}
	
	public static List<ProxyIp> getAllValidateProxy(List<ProxyIp> originList) {
		if(originList==null)return new ArrayList<ProxyIp>();
		List<ProxyIp> validatedList=new ArrayList<ProxyIp>(originList.size());
		for (ProxyIp proxyIp : originList) {
			if(isProxyValidate(proxyIp)) {
				validatedList.add(proxyIp);
			}
		}
		return validatedList;
	}
	
	public static void main(String[] args) {
		System.err.println(isProxyValidate(new ProxyIp("115.223.204.92", 9000)));
	}
	
}
